#include"chen.h"

//void str_echo(int sockfd );

extern void sig_chld( int );

int 
main(int argc, char **argv )
{
	int listenfd, connfd;
	pid_t childpid;

	struct sockaddr_in servaddr, cliaddr;
	socklen_t clilen;


	listenfd = Socket( AF_INET, SOCK_STREAM, 0 );

	bzero( &servaddr, sizeof( servaddr ) );

	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
	servaddr.sin_port = htons( SERV_PORT );

	Bind( listenfd, ( struct sockaddr * ) &servaddr, sizeof( servaddr ) );

	Listen( listenfd, 10 );

	signal( SIGCHLD, sig_chld );

	for ( ; ; ) {
		clilen = sizeof( cliaddr );
		if ( ( connfd = accept( listenfd, ( struct sockaddr * ) &cliaddr, &clilen ) ) < 0 ) {
			if ( errno == EINTR ){
				continue;
			}
			else 
				err_sys( "accept error" );
		}
	
		//connfd = Accept( listenfd, ( struct sockaddr * ) &cliaddr, &clilen );

		if ( ( childpid = Fork( ) ) == 0 ) {
			close( listenfd );
			str_echo( connfd );
			exit( 0 );
		}
		close( connfd );
	}
}

/*  
void str_echo(int sockfd )
{
	ssize_t n;
	char buf[MAXLINE];

again:
	while ( ( n = read( sockfd,buf, MAXLINE ) ) > 0 ) {
		Writen( sockfd, buf, n );
	}
	if ( n < 0 && errno == EINTR )
		goto again;
	else if ( n < 0 )
		err_sys( "str_echo error\n " );
	
}
*/
